package cn.com.dashihui.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ActiveMessageApi;
import com.jfinal.weixin.sdk.api.IntegralChangeApi;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.kit.SMSKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.AdSeller;
import cn.com.dashihui.web.dao.AuthDownload;
import cn.com.dashihui.web.dao.Seller;
import cn.com.dashihui.web.dao.Store;
import cn.com.dashihui.web.dao.User;
import cn.com.dashihui.web.exception.SaveException;
import cn.com.dashihui.web.service.AuthDownloadService;
import cn.com.dashihui.web.service.UserService;

@RequiresAuthentication
public class UserController extends BaseController{
	private UserService service = new UserService();
	private AuthDownloadService downloadService=new AuthDownloadService();
	/**
	 * 跳转团队详情页
	 */
    public void showTeam(){
    	int id = getParaToInt("id", 0);
    	int userid = getCurrentUser().get("id");//获得登录用户id
    	List<Store> storeList=service.findStoreList();
		setAttr("storeList", storeList);
    	List<AdSeller> findAdSeller = service.findAdSeller();
		setAttr("findAdSeller", findAdSeller);
		List<Seller> sellerList = service.findAllSeller();
		setAttr("sellerList", sellerList);
		setAttr("id", id);
		setAttr("userid", userid);
        render("showTeam.jsp");
    }
    /**
     * 团队详情数据
     */
    public void teampage(){
		int pageNum = getParaToInt(0, 1);
		String phone=getPara("phone");//手机号
		String card=getPara("card");//会员卡号
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		String address=getPara("address");
		String sellerid=getPara("seller");//所属公司
		int toBossThreeId = 0 ;
		if (StrKit.notBlank(sellerid)) {
			//根据dao分公司名称查询营业部id
			Seller seller = service.findSellerById(sellerid);
			toBossThreeId = seller.get("id");
		}
		String storeid=getPara("store");//所属分公司
		int toBossTwoId = 0 ;
		if (StrKit.notBlank(storeid)) {
			//根据dao分公司名称查询营业部id
			Store store = service.findStoreById(storeid);
			toBossTwoId = store.get("id");
		}
		String dao=getPara("dao");
		int toBossOneId = 0 ;
		if (StrKit.notBlank(dao)) {
			//根据dao分公司名称查询营业部id
			AdSeller adSeller = service.findAdSellerByName(dao);
			toBossOneId = adSeller.get("id");
		} 
		//会员id
		int id = getParaToInt("id", 0);
		
		String taici=getPara("taici");
		String state=getPara("state");

		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPageteam(id,pageNum, pageSize,phone,card,sBeginDate,sEndDate,address,toBossThreeId,toBossTwoId,toBossOneId,taici,state));
	}
	/**
	 * 会员信息
	 */
	public void index(){
		List<Store> storeList=service.findStoreList();
		int id = getCurrentUser().get("id");//获得登录用户id
		List<AdSeller> findAdSeller = service.findAdSeller();
		setAttr("findAdSeller", findAdSeller);
		List<Seller> sellerList = service.findAllSeller();
		setAttr("sellerList", sellerList);
		setAttr("storeList", storeList);
		setAttr("id", id);
		render("index.jsp");
	}
	/**
	 * 会员信息
	 */
	public void rewards(){
		List<Store> storeList=service.findStoreList();
		int id = getCurrentUser().get("id");//获得登录用户id
		List<AdSeller> findAdSeller = service.findAdSeller();
		setAttr("findAdSeller", findAdSeller);
		List<Seller> sellerList = service.findAllSeller();
		setAttr("sellerList", sellerList);
		setAttr("storeList", storeList);
		setAttr("id", id);
		render("rewards.jsp");
	}
	/**
     * 全部会员信息
     */
	public void pageRewards(){
		int pageNum = getParaToInt(0, 1);
		String phone=getPara("phone");//手机号
		String card=getPara("card");//会员卡号
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		String taici=getPara("taici");

		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPageRewards(pageNum, pageSize,phone,card,sBeginDate,sEndDate,taici));
	}
	/**
	* 会员积分
	*/
	public void vipindex(){
		List<Store> storeList=service.findStoreList();
		setAttr("storeList", storeList);
		render("vipindex.jsp");
	}
	/**
     * 全部会员信息
     */
	public void page(){
		int pageNum = getParaToInt(0, 1);
		String phone=getPara("phone");//手机号
		String name=getPara("name");//姓名
		String card=getPara("card");//会员卡号
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		String address=getPara("address");
		String sellerid=getPara("seller");//所属公司
		int toBossThreeId = 0 ;
		if (StrKit.notBlank(sellerid)) {
			//根据dao分公司名称查询营业部id
			Seller seller = service.findSellerById(sellerid);
			toBossThreeId = seller.get("id");
		}
		String storeid=getPara("store");//所属分公司
		int toBossTwoId = 0 ;
		if (StrKit.notBlank(storeid)) {
			//根据dao分公司名称查询营业部id
			Store store = service.findStoreById(storeid);
			toBossTwoId = store.get("id");
		}
		String dao=getPara("dao");
		int toBossOneId = 0 ;
		if (StrKit.notBlank(dao)) {
			//根据dao分公司名称查询营业部id
			AdSeller adSeller = service.findAdSellerByName(dao);
			toBossOneId = adSeller.get("id");
		} 
		String taici=getPara("taici");
		String state=getPara("state");

		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPage(pageNum, pageSize,name,phone,card,sBeginDate,sEndDate,address,toBossThreeId,toBossTwoId,toBossOneId,taici,state));
	}

	/**
	 * 发送消息
	 */
	public void message(){
		String ids="";
		String phone=getPara("phone");
		String card=getPara("card");
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		String beginDate=getPara("beginDate");//办卡
		String endDate=getPara("endDate");
		String store=getPara("store");
		String title="";
		if(StrKit.notBlank(store)){
			 List<Store> st=service.findStoreByIds(store);
			 for (int i = 0; i < st.size(); i++) {
				if(i==0){
					title=st.get(i).get("title");
				}else{
					title+="','"+st.get(i).get("title");
				}
			}
		}
		String dao=getPara("dao");
		String taici=getPara("taici");
		String state=getPara("state");
		List<Record> list=service.findMesageList(phone,card,sBeginDate,sEndDate,beginDate,endDate,title,dao,taici,state);
		for (int i = 0; i < list.size(); i++) {
			if(i==0){
				ids=list.get(i).get("phone");
			}else{
				ids+=","+list.get(i).get("phone");
			}
		}
		setAttr("ids", ids);
		render("sendMessage.jsp");
	}
	/**
	 * 列表查询
	 */
	public void vippage(){
		int pageNum = getParaToInt(0, 1);
		String phone=getPara("phone");
		String card=getPara("card");
		String store=getPara("store");
		int toBossTwoId = 0;
		if(StrKit.notBlank(store)){
			 Store st=service.findStoreById(store);
			 toBossTwoId=st.get("id");
		 }
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByVipPages(pageNum, pageSize,phone,card,toBossTwoId));
	}
	/**
	 * 会员积分统计
	 */
	public void vippage1(){
		String index=getPara("index");
		int pageNum = getParaToInt(0, 1);
		String phone=getPara("phone");
		String card=getPara("card");
		String store=getPara("store");
		String title="";
		if(StrKit.notBlank(store)){
			 Store st=service.findStoreById(store);
			 title=st.getStr("title");
		 }
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByVipPages1(pageNum, pageSize,index,phone,card,title));
	}
	/**
	 * 手机短信
	 */
	public void sendMessage(){
		String ids=getPara(0);
		setAttr("ids", ids);
		render("sendMessage.jsp");
	}
	public void doSendMessage(){
		String ids = getPara("ids");
		String message = getPara("message");
		List<String> phoneList = new ArrayList<String>();
		int subLen = 100 * 12;
		int xh = 0;//循环次数
		int a = ids.length() % subLen;
		xh = ids.length()/subLen;
		if(a > 0) {
			xh += 1;
		}
		for(int i = 0; i < xh; i++){
			if(i==xh-1){
				phoneList.add(ids.substring(i*subLen));
			}else{
				phoneList.add(ids.substring(i*subLen, i*subLen + subLen-1));
			}
		}
		for (String phone : phoneList) {
			SMSKit.sendSms(phone, message);
		}
		renderSuccess();
	}
	/**
	 * 添加会员
	 */
	public void toAdd(){
		List<Store> storeList=service.findStoreList();
		List<Seller> sellerList = service.findAllSeller();
		setAttr("sellerList", sellerList);
		setAttr("storeList", storeList);
		render("add.jsp");
	}
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：用户名为空，2：用户名格式不正确，3：用户已经存在，4：密码为空，5：密码格式不正确，6：密码长度不正确，7：昵称为空，8：昵称过长
	 */
	public void doAdd(){
		//电话
		String aphone = getPara("aphone");
		//姓名
		String aname = getPara("aname");
		//性别
		int sex = getParaToInt("radio");
		String birthday = getPara("birthday");
		String yuchan = getPara("yuchanthday");
		String babythday = getPara("babythday");
		int taici = getParaToInt("taici");
		String province = getPara("province");
		String city = getPara("city");
		String area = getPara("area");
		String address = getPara("address");
		int state = getParaToInt("state");
		String sellerid = getPara("seller");
		String storeid = getPara("store");
		Seller seller = service.findSellerById(sellerid);
		int seid = seller.get("id");
		Store store = service.findStoreById1(storeid);
		int stid = store.get("id");
		String trueName = getPara("toBossOneId");
		int adid = 0;
		if (StrKit.notBlank(trueName)) {
			AdSeller adSeller = service.findAdSellerByName(trueName);
			adid = adSeller.get("id");
		}
		String addressa=province+city+area;
		if(StrKit.notBlank(address)){
			addressa=addressa+address;
		}
		User newUser=service.findByPhone(aphone);
		if (newUser!=null) {
			 renderFailed("手机号已经存在");
			 return;
		}
		 String cards=DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS");
		 String card=cards.substring(2);
		 User user=new User();
		//设置用户密码，默认为手机号后六位
		 String password = aphone.substring(aphone.length() - 6);
		 
		 user.set("name", aname)
		 	 .set("card", card)
		 	 .set("phone", aphone)
		 	 .set("password", CommonKit.encryptPassword(password))
		 	 .set("sex", sex)
		 	 .set("birthday", birthday)
		 	 .set("state", state)
		 	 .set("address", addressa)
		 	 .set("toBossThreeId", seid)
		 	 .set("toBossTwoId", stid)
		 	 .set("toBossOneId", adid)
		 	 .set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
		 if(StrKit.notBlank(yuchan)){
			 user.set("babythday", yuchan);
		 }
		 if(StrKit.notBlank(babythday)){
			 user.set("babythday", babythday);
		 }
		 if(taici !=0){
			 user.set("taici", taici);
		 }
		
		 if(adid!=0){
			 user.set("toBossOneId", adid);
		 }
		 if(service.addUser(user)){
			renderSuccess();
			return;
		 }
		renderFailed();
	}
	/**
	 * 会员详情
	 */
	public void detail(){
		int id = getParaToInt(0,0);
		if(id!=0){
		User user=service.findUserById(id);
			setAttr("user", user);
			List<Store> storeList=service.findStoreList();
			setAttr("storeList", storeList);
			List<Record> daoList=service.findDaoList();
			setAttr("daoList", daoList);
			List<Record> userList=service.findUserList(user.get("store"));
			setAttr("userList", userList);
		}
		render("detail.jsp");
	}
	/**
	 * 会员积分详情
	 */
	public void detailVip(){
		try {
			int id = getParaToInt(0,0);
			if(id!=0){
				User user=service.findById(id);
				setAttr("user", user);
				//获取所属的store
				int stid = user.get("toBossTwoId");
				/*线下积分消费明细*/
				List<Record> offJfOrderList=service.findOffJfOrderList(user.get("phone"));
				setAttr("offJfOrderList", offJfOrderList);
				/*线下订单明细*/
//				List<Record> offOrderList=service.findOffOrderList(user.get("phone"));
//				setAttr("offOrderList", offOrderList);
				
				/*线上订单明细*/
				List<Record> orderList=service.findOrderList(id);
				setAttr("orderList", orderList);
			}
			render("detailVip.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 验证手机号
	 */
	public void validate(){
		String phone=getPara("aphone");
		User user=service.findByPhone(phone);
		if (StrKit.notNull(user)) {
			renderFailed();
			return;
		}else{
			renderSuccess();
			return;
		}
	}
	/**
	 * 选择分公司
	 */
	public void chooseStore(){
		String[] seller = getParaValues("seller");
		String str = java.lang.String.join("','", seller);
		renderSuccess(service.chooseStore(str));
	}
	/**
	 * 选择营业部
	 */
	public void chooseDao(){
		String[] store = getParaValues("store");
		String str = java.lang.String.join("','", store);
		renderSuccess(service.chooseDao(str));
	}
	
	/**
	 * 到发送微信服务号模板消息页面
	 */
	public void sendTemplate(){
		String ids="";
		String phone=getPara("phone");
		String card=getPara("card");
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		String beginDate=getPara("beginDate");//办卡
		String endDate=getPara("endDate");
		String store=getPara("store");
		String title="";
		if(StrKit.notBlank(store)){
			 List<Store> st=service.findStoreByIds(store);
			 for (int i = 0; i < st.size(); i++) {
				if(i==0){
					title=st.get(i).get("title");
				}else{
					title+="','"+st.get(i).get("title");
				}
			}
		 }
		String dao=getPara("dao");
		String taici=getPara("taici");
		String state=getPara("state");
		//取得条件检索出的会员的电话集合
		List<Record> list=service.findMesageList(phone,card,sBeginDate,sEndDate,beginDate,endDate,title,dao,taici,state);
		
		for (int i = 0; i < list.size(); i++) {
			if(i==0){
				ids=list.get(i).get("phone");
			}else{
				ids+=","+list.get(i).get("phone");
			}
		}
		setAttr("ids", ids);
		render("sendTemplate.jsp");
	}
	/**
	 * 发送微信服务号模板消息
	 */
	@SuppressWarnings("static-access")
	public void doSendTemplate(){
		String ids = getPara("ids");//推送的会员手机号
		String active = getPara("words");//活动名称
		String storeName = getPara("storeName");//活动名称
		String startDate = getPara("startDate");//活动开始时间
		String endDate = getPara("endDate");//活动结束时间
		String jieWei = getPara("jieWei");//活动结束时间
		//跳转路径
		String url = getPara("url");
		String[] phones = ids.split(",");
		List<String> phoneList = Arrays.asList(phones);
		
		String firstDATA=active;					
		String keyword1DATA=storeName;
		String keyword2DATA=startDate+" - "+endDate;
		String remarkDATA=jieWei;
		
				//跳转路径
		if(StrKit.isBlank(url)){
			url="http://test.bain.net.cn";
		}
				String inviteOpenid = "";
				
				Map<String,Object> map2 = new HashMap<String,Object>();
				
				map2.put("firstDATA", firstDATA);
				map2.put("keyword1DATA", keyword1DATA);
				map2.put("keyword2DATA", keyword2DATA);
				map2.put("remarkDATA", remarkDATA);
				map2.put("url", url);
		List<Record> openidList = service.findWxOpenIdDao(phoneList);
		
		for(Record wxOpenId : openidList){
			try {
				Thread.currentThread();
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			inviteOpenid = wxOpenId.getStr("openid");
			map2.put("OPENID", inviteOpenid);
			try {
				System.out.println("模板消息推送");

				ActiveMessageApi.editWX_opinion(map2);
			} catch (SaveException e) {
				System.out.println("模板消息推送失败");
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		renderSuccess();
	}
	
	/**
	 * 编辑会员
	 */
	public void doEdit(){
		int userid=getParaToInt("userid",0);
		
		String sppoint=getPara("sppoint");
		String jypoint=getPara("jypoint");
		String jkpoint=getPara("jkpoint");
		
		String phone=getPara("phone");
		String store=getPara("store");
		String name=getPara("name");
		String toBossOneId=getPara("toBossOneId");
		System.out.println(toBossOneId);
		if(userid !=0){
			User user=service.findById(userid);
			if(StrKit.notNull(user)){

				// 计算订单总积分

				String point = "";//积分
				//积分变化前的积分
				int sppoi = user.getInt("sppoint");
				int jkpoi = user.getInt("jkpoint");
				int jypoi = user.getInt("jypoint");
				
				if(StrKit.notBlank(phone)){
					if(!user.get("phone").equals(phone)){
						User users=service.findByPhone(phone);
						if(StrKit.notNull(users)){
							renderResult(2);
							return;
						}else{
							user.set("phone", phone);
						}
					}
				}
				if (StrKit.notBlank(name)) {
					user.set("name", name);
				}
				//积分变动推送  计算积分是增加还是减少
				int c=0,c1=0,c2=0;
				if(StrKit.notBlank(sppoint)){
					 c=Integer.parseInt(sppoint)-sppoi;
				}
				if(StrKit.notBlank(jkpoint)){
					 c1=Integer.parseInt(jkpoint)-jkpoi;
				}
				if(StrKit.notBlank(jypoint)){
					 c2=Integer.parseInt(jypoint)-jypoi;
				}
				if(c>0){
					point+="积分:"+"+"+c+" ";
				}else if(c<0){
					point+="积分:"+c+" ";
				}else{
					point+="积分:"+"无"+" ";
				}
				if(c1>0){
					point+="抵扣券:"+"+"+c1+" ";
				}else if(c1<0){
					point+="抵扣券:"+c1+" ";
				}else{
					point+="抵扣券:"+"无"+" ";
				}
				if(c2>0){
					point+="惠券:"+"+"+c2+" ";
				}else if(c2<0){
					point+="惠券:"+c2+" ";
				}else{
					point+="惠券:"+"无"+" ";
				}
				
				
				
				if(StrKit.notBlank(jypoint)){
					user.set("jypoint", jypoint);					
				}
				if(StrKit.notBlank(sppoint)){
				
					user.set("sppoint", sppoint);
				}
				if(StrKit.notBlank(jkpoint)){
					
					user.set("jkpoint", jkpoint);
				}
				if (StrKit.notBlank(store)) {
					Store st = service.findStoreById(store);
					user.set("toBossTwoId", st.get("id"));
				}
				if(StrKit.notBlank(store)&&StrKit.notBlank(toBossOneId)){
					user.set("toBossOneId", toBossOneId);
				}else if(StrKit.notBlank(store)&&StrKit.isBlank(toBossOneId)){
					user.set("toBossOneId", 0);
				}
				 if(user.update()){
//					 try {
//						 service.setPhone(phone, oldPhone);
//						} catch (Exception e) {
//							// TODO: handle exception
//							log.info("第三方更新电话失败");
//						}
					 //如果积分变动发送积分变动消息
					   if(c!=0 ||c1!=0||c2!=0){						   					  
							//查询积分变更后的积分
							User userAfter = service.findById(userid);
							String firstDATA="您的积分账户有新的变动，详情如下：";					
							String keyword1DATA=user.get("name")+"";
							String keyword2DATA=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
							String keyword3DATA=point+"";	
							String keyword4DATA="积分:"+userAfter.get("sppoint")+","+"惠券:"+userAfter.get("jypoint")+","+"抵扣券"+userAfter.get("jkpoint");	
							String keyword5DATA="转增积分";	
							String remarkDATA="如有疑问可联系分公司";
	
							String inviteOpenid = service.findByWxUser(userid).getStr("openid");
							//跳转路径
							String url="http://test.bain.net.cn";
							
							Map<String,Object> map2 = new HashMap<String,Object>();
							map2.put("OPENID", inviteOpenid);
							map2.put("firstDATA", firstDATA);
							map2.put("firstDATA", firstDATA);
							map2.put("keyword1DATA", keyword1DATA);
							map2.put("keyword2DATA", keyword2DATA);
							map2.put("keyword3DATA", keyword3DATA);
							map2.put("keyword4DATA", keyword4DATA);
							map2.put("keyword5DATA", keyword5DATA);
							map2.put("remarkDATA", remarkDATA);
							map2.put("url", url);
	
							try { 
								System.out.println("积分变动通知消息推送");
	
								IntegralChangeApi.editWX_opinion(map2);
							} catch (SaveException e) {
								System.out.println("积分变动通知推送失败");
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					   }
					 
					 renderSuccess(service.findById(userid));
					 return;
				 }else{
					 renderFailed();
						return;
				 }
			}else{
				renderFailed();
				return;
			}
		}else{
			renderFailed();
			return;
		}
	}
	/**
	 * excel导出
	 */
	public void doVipExcel(){
		List<Pair> titles = new ArrayList<Pair>();
	    titles.add(new Pair("card", "会员卡号"));
	    titles.add(new Pair("name", "会员姓名"));
	    titles.add(new Pair("phone", "会员手机号"));
	    titles.add(new Pair("storeName", "所属分公司"));
	    titles.add(new Pair("trueName", "营业部"));
	    titles.add(new Pair("createDate", "办卡日期"));
	    titles.add(new Pair("sppoint", "积分"));
	    titles.add(new Pair("jkpoint", "抵扣券"));
	    titles.add(new Pair("jypoint", "惠券"));
	    String phone=getPara("phone");
		String card=getPara("card");
		String store=getPara("store");
		String title="";
		if(StrKit.notBlank(store)){
			 Store st=service.findStoreById(store);
			 title=st.getStr("title");
		 }
		 
		List<Record> list=service.findExcelVipByPage(phone,card,title);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
				record.set("card",list.get(i).get("card"));
				record.set("name", list.get(i).get("name"));
				record.set("phone", list.get(i).get("phone"));
				record.set("storeName", list.get(i).get("storeName"));
				record.set("trueName", list.get(i).get("trueName"));
				record.set("createDate", list.get(i).get("createDate"));
				record.set("sppoint", list.get(i).get("sppoint"));
				record.set("jkpoint", list.get(i).get("jkpoint"));
				record.set("jypoint", list.get(i).get("jypoint"));
			listz.add(record);
 		}

		//向登录下载统计表中添加数据 会员积分统计
		Record downObj=downloadService.findByUserId(getCurrentUser().getInt("id"));
		AuthDownload download=new AuthDownload();
		download.set("logName","平台端")
			        .set("name", downObj.get("trueName"))
			        .set("accountRole", downObj.get("alias"))
			        .set("storeName", "公司总部")
			        .set("integralDownload", 1)
                   .set("downloadDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));

		download.save();
		// 导出
		service.exportVip(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	/**
	 * excel导出
	 */
	public void doExcel(){
		List<Pair> titles = new ArrayList<Pair>();
	    titles.add(new Pair("card", "会员卡号"));
	    titles.add(new Pair("name", "会员姓名"));
	    titles.add(new Pair("phone", "会员手机号"));
	    titles.add(new Pair("sellerName", "所属公司"));
	    titles.add(new Pair("storeName", "所属分公司"));
	    titles.add(new Pair("trueName", "营业部"));
	    titles.add(new Pair("userNum", "团队人数"));
	    titles.add(new Pair("pareName", "邀请人"));
	    titles.add(new Pair("createDate", "办卡日期"));
	    titles.add(new Pair("birthday", "会员生日"));
	    titles.add(new Pair("state", "会员状态"));
	    titles.add(new Pair("taici", "等级"));
	    titles.add(new Pair("babythday", "升级日期"));
	    titles.add(new Pair("address", "会员地址"));
	    titles.add(new Pair("countnum", "消费次数"));
	    titles.add(new Pair("guanzhu", "关注"));
	    String phone=getPara("phone");
		String card=getPara("card");
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		String beginDate=getPara("beginDate");//办卡
		String endDate=getPara("endDate");
		String store=getPara("store");
		String address=getPara("address");
		String id="";
		if(StrKit.notBlank(store)){
			 List<Store> st=service.findStoreByIds(store);
			 for (int i = 0; i < st.size(); i++) {
				if(i==0){
					id=st.get(i).get("id");
				}else{
					id+="','"+st.get(i).get("id");
				}
			}
		 }
		String dao=getPara("dao");
		String taici=getPara("taici");
		String state=getPara("state");
		List<Record> list=service.findExcelByPage(phone,card,sBeginDate,sEndDate,beginDate,endDate,address,id,dao,taici,state);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			list.get(i).get("taici");
			Record record=new Record();
				record.set("card",list.get(i).get("card"));
				record.set("name", list.get(i).get("name"));
				record.set("phone", list.get(i).get("phone"));
				record.set("birthday", list.get(i).get("birthday"));
				if(list.get(i).get("state").equals(1)){
					record.set("state", "未登录");
				}else if(list.get(i).get("state").equals(2)){
					record.set("state", "未注册");
				}else if(list.get(i).get("state").equals(3)){
					record.set("state", "会员");
				}
				if(list.get(i).get("taici").equals(1)){
					record.set("taici", "会员");
				}else if(list.get(i).get("taici").equals(2)){
					record.set("taici", "黄金");
				}else if(list.get(i).get("taici").equals(3)){
					record.set("taici", "白金");
				}else if(list.get(i).get("taici").equals(4)){
					record.set("taici", "经纪人");
				}else if(list.get(i).get("taici").equals(5)){
					record.set("taici", "营业部");
				}else if(list.get(i).get("taici").equals(6)){
					record.set("taici", "分公司");
				}else if(list.get(i).get("taici").equals(7)){
					record.set("taici", "公司");
				}
				record.set("babythday", list.get(i).get("babythday"));
				record.set("allCount", list.get(i).get("allCount"));
				if( list.get(i).get("excnum")==null){
					record.set("excnum","0");
				}else{
					record.set("excnum", list.get(i).get("excnum"));
				}
				record.set("countnum", list.get(i).get("countnum"));
				record.set("storeName", list.get(i).get("storeName"));
				record.set("trueName", list.get(i).get("trueName"));
				record.set("sellerName", list.get(i).get("sellerName"));
				record.set("createDate", list.get(i).get("createDate"));
				record.set("address", list.get(i).get("address"));
				if(list.get(i).get("guanzhu").equals(1)){
					record.set("guanzhu", "");
				}else if(list.get(i).get("guanzhu").equals(2)){
					record.set("guanzhu", "是");
				}
				if(list.get(i).get("userNum")!=null){
					record.set("userNum", list.get(i).get("userNum"));
				}else{
					record.set("userNum", 0);
				}
				record.set("pareName", list.get(i).get("pareName"));
			listz.add(record);
 		}

		//向登录下载统计表中添加数据 会员信息统计
		Record downObj=downloadService.findByUserId(getCurrentUser().getInt("id"));
		AuthDownload download=new AuthDownload();
		download.set("logName","平台端")
			        .set("name", downObj.get("trueName"))
			        .set("accountRole", downObj.get("alias"))
			        .set("storeName", "公司总部")
			        .set("memberDownload", 1)
                   .set("downloadDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));

		download.save();
 
		// 导出
		service.export(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	/**
	 * excel导出
	 */
	public void doExcelRewards(){
		List<Pair> titles = new ArrayList<Pair>();
	    titles.add(new Pair("card", "会员卡号"));
	    titles.add(new Pair("name", "会员姓名"));
	    titles.add(new Pair("phone", "会员手机号"));
	    titles.add(new Pair("taici", "等级"));
	    titles.add(new Pair("countnum", "消费次数"));
	    titles.add(new Pair("totalMoney", "消费金额"));
	    titles.add(new Pair("totalPoint", "邀请奖励"));

	    String phone=getPara("phone");
		String card=getPara("card");
		String sBeginDate=getPara("sBeginDate");//开始日期
		String sEndDate=getPara("sEndDate");//结束日期
		String id="";
		String taici=getPara("taici");

		List<Record> list=service.doExcelRewards(phone,card,sBeginDate,sEndDate,id,taici);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			list.get(i).get("taici");
			Record record=new Record();
				record.set("card",list.get(i).get("card"));
				record.set("name", list.get(i).get("name"));
				record.set("phone", list.get(i).get("phone"));
				if(list.get(i).get("taici").equals(1)){
					record.set("taici", "会员");
				}else if(list.get(i).get("taici").equals(2)){
					record.set("taici", "黄金");
				}else if(list.get(i).get("taici").equals(3)){
					record.set("taici", "白金");
				}else if(list.get(i).get("taici").equals(4)){
					record.set("taici", "经纪人");
				}else if(list.get(i).get("taici").equals(5)){
					record.set("taici", "营业部");
				}else if(list.get(i).get("taici").equals(6)){
					record.set("taici", "分公司");
				}else if(list.get(i).get("taici").equals(7)){
					record.set("taici", "公司");
				}
				record.set("countnum", list.get(i).get("countnum"));
				record.set("totalMoney", list.get(i).get("totalMoney"));
				record.set("totalPoint", list.get(i).get("totalPoint"));
				record.set("pareName", list.get(i).get("pareName"));
			listz.add(record);
 		}

		//向登录下载统计表中添加数据 会员信息统计
		Record downObj=downloadService.findByUserId(getCurrentUser().getInt("id"));
		AuthDownload download=new AuthDownload();
		download.set("logName","平台端")
			        .set("name", downObj.get("trueName"))
			        .set("accountRole", downObj.get("alias"))
			        .set("storeName", "公司总部")
			        .set("memberDownload", 1)
                   .set("downloadDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));

		download.save();
 
		// 导出
		service.export(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	
	/**
	 * 历史业绩信息
	 */
    public void historyAmount(){
    	List<Store> storeList=service.findStoreList();
    	int id = getCurrentUser().get("id");//获得登录用户id
    	List<AdSeller> findAdSeller = service.findAdSeller();
		setAttr("findAdSeller", findAdSeller);
		List<Seller> sellerList = service.findAllSeller();
		setAttr("sellerList", sellerList);
		setAttr("storeList", storeList);
		setAttr("id", id);
        render("historyAmount.jsp");
    }
    
    /**
     * 全部历史业绩信息
     */
	public void queryHistoryAmount(){
		int pageNum = getParaToInt(0, 1);
		String card=getPara("card");//会员卡号
		String name=getPara("name");//会员姓名
		String phone=getPara("phone");//会员手机号
		String sBeginDate=getPara("sBeginDate");//办卡日期
		String sEndDate=getPara("sEndDate");

		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.queryHistoryAmountByPage(pageNum, pageSize,card,name,phone,sBeginDate,sEndDate));
	}
	
	/**
	 * excel导出 历史业绩查询
	 */
	public void doExcelHistory(){
		List<Pair> titles = new ArrayList<Pair>();
		titles.add(new Pair("id", "会员ID"));
		titles.add(new Pair("createDate", "日期"));
	    titles.add(new Pair("card", "会员卡号"));
	    titles.add(new Pair("phone", "会员手机号"));
	    titles.add(new Pair("name", "会员昵称"));
	    titles.add(new Pair("custName", "会员姓名"));
	    titles.add(new Pair("userNum", "新增人数"));
	    titles.add(new Pair("ficum", "新增交易量"));
	    titles.add(new Pair("finum", "新增交易额"));
	    titles.add(new Pair("seuserNum", "复投人数"));
	    titles.add(new Pair("secum", "复投交易量"));
	    titles.add(new Pair("senum", "复投交易额"));
	    titles.add(new Pair("allCount", "总考核金额"));
		String card=getPara("card");
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		List<Record> list=service.findExcelHistory(card,sBeginDate,sEndDate);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
			record.set("id",list.get(i).get("id"));
			record.set("createDate",list.get(i).get("createDate"));
			record.set("card",list.get(i).get("card"));
			record.set("phone", list.get(i).get("phone"));
			record.set("name", list.get(i).get("name"));
			record.set("custName", list.get(i).get("custName"));
			record.set("userNum", list.get(i).get("userNum"));
			record.set("ficum", list.get(i).get("ficum"));
			record.set("finum", list.get(i).get("finum"));
			record.set("seuserNum", list.get(i).get("seuserNum"));
			record.set("secum", list.get(i).get("secum"));
			record.set("senum", list.get(i).get("senum"));
			record.set("allCount", list.get(i).get("allCount"));
			listz.add(record);
 		}

		//向登录下载统计表中添加数据 
		Record downObj=downloadService.findByUserId(getCurrentUser().getInt("id"));
		AuthDownload download=new AuthDownload();
		download.set("logName","平台端")
			        .set("name", downObj.get("trueName"))
			        .set("accountRole", downObj.get("alias"))
			        .set("storeName", "公司总部")
			        .set("memberDownload", 1)
                   .set("downloadDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
		download.save();
 
		// 导出
		service.exportHistory(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	/**
	 * 提现
	 */
	public void tomoney(){
		List<Seller> list=service.findAllSeller();
    	setAttr("list", list);
		render("tomoney.jsp");
	}
	/**
	 * 获得订单列表数据
	 */
	public void pageMoney(){
		System.out.println("获得订单列表数据");
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		//订单编号
		String orderNum = getPara("orderNum");
		//下单时间范围
		String beginDate = getPara("beginDate");
		String endDate = getPara("endDate");
		//订单状态
		int state = getParaToInt("state",0);
		//提现用户电话
		String tel = getPara("tel");
		//提现用户姓名
		String name = getPara("name");
		//公司ID
		String sellerId=getPara("sellerId");
		//分公司ID
		String storeId=getPara("storeId");
		Page<Record> findByPage = service.findByPageMoney(pageNum,pageSize,orderNum,beginDate,endDate,state,sellerId,tel,name,storeId);
		renderResult(0,findByPage);
	}
	//去审核提现申请
	public void toMoneyAccept(){
		String orderNum = getPara("orderNum");
		setAttr("orderNum", orderNum);
		render("accept.jsp");
	}
	//去驳回提现申请
	public void toMoneyCancel(){
		String orderNum = getPara("orderNum");
		setAttr("orderNum", orderNum);
		render("cancel.jsp");
	}
	//去通过提现申请
		public void doMoneyAccept(){
			String orderNum = getPara("orderNum");
			String payNum = getPara("payNum");
			String otherMoney = getPara("otherMoney");
			int count = service.doMoneyAccept(orderNum,payNum,otherMoney);
			System.out.println("LLLLLLLLLLLLLL"+(count==1));
			if ( count == 1){
				//成功
				renderSuccess(service.findEcardByorderNum(orderNum));
				return;
			}else if ( count == -1 ) {
				//没有该笔订单
				renderFailed("没有该笔订单");
				return;
			}else if ( count== -2 ){
				//更改提现订单状态失败
				logger.debug("更改提现订单状态失败");
				renderFailed("网络异常，请稍后重试");
				return;
			}
		}
		//驳回
		public void doMoneyCancel(){
			String orderNum = getPara("orderNum");
			String describe = getPara("describe");
			int count;
			try {
				count = service.doMoneyCancel(orderNum,describe);
				System.out.println("LLLLLLLLLLLLLL"+(count==1));
				if ( count == 1){
					//成功
					renderSuccess(service.findEcardByorderNum(orderNum));
					return;
				}else if ( count == -1 ) {
					//没有该笔订单
					renderFailed("没有该笔订单");
				}else if ( count== -2 ){
					//更改提现订单状态失败
					logger.debug("更改提现订单状态失败");
					renderFailed("网络异常，请稍后重试");
					return;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.debug(e.getMessage());
				renderFailed("网络异常，请稍后重试");
				return;
			}
			
		}
	/**
	 * 退款单信息
	 */
	public void tui(){
		List<Store> storeList=service.findStoreList();
		int id = getCurrentUser().get("id");//获得登录用户id
		List<AdSeller> findAdSeller = service.findAdSeller();
		setAttr("findAdSeller", findAdSeller);
		List<Seller> sellerList = service.findAllSeller();
		setAttr("sellerList", sellerList);
		setAttr("storeList", storeList);
		setAttr("id", id);
		render("tui.jsp");
	}
	/**
	 * 会员财务信息
	 */
	public void userMoneyDetail(){
		List<Store> storeList=service.findStoreList();
		int id = getCurrentUser().get("id");//获得登录用户id
		List<AdSeller> findAdSeller = service.findAdSeller();
		setAttr("findAdSeller", findAdSeller);
		List<Seller> sellerList = service.findAllSeller();
		setAttr("sellerList", sellerList);
		setAttr("storeList", storeList);
		setAttr("id", id);
		render("userMoneyDetail.jsp");
	}
	/**
	 * 会员充值信息
	 */
	public void recharge(){
		int id = getParaToInt("id");
		setAttr("userId", id);
		render("recharge.jsp");
	}
	/**
	 * 会员提现信息
	 */
	public void extract(){
		int id = getParaToInt("id");
		setAttr("userId", id);
		render("extract.jsp");
	}
	/**
	 * 订单统计查询所需积分总和现金价格总和
	 */
	public void findTotal(){
		String phone=getPara("phone");//手机号
		String name=getPara("name");//姓名
		String card=getPara("card");//会员卡号
		String sBeginDate=getPara("sBeginDate");//生日
		String sEndDate=getPara("sEndDate");
		String address=getPara("address");
		String sellerid=getPara("seller");//所属公司
		int toBossThreeId = 0 ;
		if (StrKit.notBlank(sellerid)) {
			//根据dao分公司名称查询营业部id
			Seller seller = service.findSellerById(sellerid);
			toBossThreeId = seller.get("id");
		}
		String storeid=getPara("store");//所属分公司
		int toBossTwoId = 0 ;
		if (StrKit.notBlank(storeid)) {
			//根据dao分公司名称查询营业部id
			Store store = service.findStoreById(storeid);
			toBossTwoId = store.get("id");
		}
		String dao=getPara("dao");
		int toBossOneId = 0 ;
		if (StrKit.notBlank(dao)) {
			//根据dao分公司名称查询营业部id
			AdSeller adSeller = service.findAdSellerByName(dao);
			toBossOneId = adSeller.get("id");
		} 
		String taici=getPara("taici");
		String state=getPara("state");

		renderSuccess(service.findTotal(name,phone,card,sBeginDate,sEndDate,address,toBossThreeId,toBossTwoId,toBossOneId,taici,state));
	}
}